import time
import datetime
import psycopg2
import requests


url = "http://vminsert-sre.xiaopeng.link/insert/0/prometheus/api/v1/import/prometheus"
# 保存上一次的slave地址

pg_instance = 'pgm-0jl893158185tu74'

def push_simple_metric(metric_name, value, job='pg-custom-exporter', instance='localhost', gateway_url=''):
    metric_data = f'{metric_name}{{cluster="wulan-prod", job="{job}", instanceId="{pg_instance}" }} {value}'
    # print(metric_data)
    response = requests.post(gateway_url, data=metric_data)
    if response.status_code in (200, 204):
        print(f"Metric '{metric_name}' with value {value} pushed successfully.")
    else:
        print(f"Failed to push metric '{metric_name}'. Response code: {response.status_code}")


def create_conn():
    while True:
        try:
            conn = psycopg2.connect(dbname='postgres', user='xxxx', password='xxx',host='ssssssxxxxxxxx', port=5432)
            return conn
        except Exception as e :
            time.sleep(3)

old_slave_client = ''
state_cnt = 0
while True:
    conn = create_conn()
    cur = conn.cursor()
    cur.execute("select client_addr from pg_stat_replication;")
    res = cur.fetchone()
    cur.close()
    conn.close()
    while res is None:
        print("res is None 重新执行语句")
        conn = create_conn()
        cur = conn.cursor()
        cur.execute("select client_addr from pg_stat_replication;")
        res = cur.fetchone()
        cur.close()
        conn.close()
    current_slave_client = res[0]
    print("[" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "]" + old_slave_client, current_slave_client)
    state = 0 # 0 表示主从未切换，1 表示主从切换了
    if old_slave_client == '':
        old_slave_client = current_slave_client
    else :
        if current_slave_client == old_slave_client:
            state = 0
            state_cnt = 0
        else:
            state = 1
            state_cnt = state_cnt + 1
        print("[" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "] pg_master_slave_switch{cluster=\"wulan-prod\", instanceId=\"" + pg_instance + "\"} " + str(state))


    if state == 1 and state_cnt>5:
        old_slave_client = current_slave_client
    push_simple_metric("pg_master_slave_switch", state, gateway_url=url)

    time.sleep(30)